#! /usr/bin/env python
import shutil
import os
import time
import datetime
import math
import urllib
import urllib2
import sys
import pylzma
from py7zlib import Archive7z, NoPasswordGivenError, WrongPasswordError

StartScript = None

if len(sys.argv) > 1:
	if sys.argv[1] == "-start":
		print "Start parameter found. Starting script when updated"
		StartScript = sys.argv[2]
	if sys.argv[1] == "-h":
		print "This script will update your local copy of bisounours party."
		print "You can make this script automatically run the server by adding"
		print " -start /path/to/end/script.sh"
		print "This will skip any wait and run your script that launch the server"
		sys.exit()

print "Checking local version of game"
LocalFile = open('version', 'r')
LocalVersion = LocalFile.read()
print 'Local version is ' + LocalVersion

print "Checking last version of game"
filehandle = urllib.urlopen('http://www.bisounoursparty.com/Cloud/lastversion.php')
LastVersion = filehandle.read()
filehandle.close()
print "Last version of the game is " + LastVersion
Iterations = int(LastVersion) - int(LocalVersion)
print "You need to do " + str(Iterations) + " updates"
if(Iterations <= 0):
	print "No new update needed. Exiting."
	sys.exit()
print "Preparing to upate " + str(Iterations) + " times."
if StartScript is None:
	raw_input("Press Enter to continue...")
i = 0
while(i < Iterations):
	i += 1
	PatchNbr = str(int(LocalVersion) + i)
	print "Downloading patch #" + PatchNbr
	UpdateFile = urllib2.urlopen("http://www.bisounoursparty.com/updates/"+PatchNbr+".update")
	output = open('../updates/'+PatchNbr+'.patch','wb')
	output.write(UpdateFile.read())
	output.close()
	# Download the file and store it
	fp = file('../updates/'+PatchNbr+'.patch','rb')
	print "Downloaded patch, Extracting"
	archive = Archive7z(fp)
	files = archive.getmembers()
	for f in files: 
	# Open the archive and extract it's files
		outfile = open('../'+f.filename, 'wb')
		outfile.write(f.read())
		outfile.close()
	fp.close()
	print "Cleaning up Patch file"
	os.remove('../updates/'+PatchNbr+'.patch')
print "You now have the latest version of the game"
# We don't want to launch a script, quit now
if StartScript is None:
	sys.exit()

print "Running end script"
os.system(StartScript)
